/*
 * FileWriter.cpp
 *
 *  Created on: Jun 30, 2011
 *      Author: tflanzer
 */

#include "FileWriter.h"
#include <time.h>
#include <string>

FileWriter::FileWriter() {

	string date = getDate();

	// Open file to record data
	Sfile = new ofstream ("stateout.txt");

	// Load parameter names
	loadNames();

	// Initialize parameter values
	initializeValues();

	// Writer header
	writeFileHeader();
}

FileWriter::~FileWriter() {
}

void FileWriter::writeFileHeader() {
	for (int i = 0; i < noutput; i++) {
		*Sfile << pnames[i] << ",";
	}
	*Sfile << endl;
}

void FileWriter::updateValue(string name, double val) {
	out[name] = val;
}

void FileWriter::initializeValues() {
	for (int i = 0; i < noutput; i++) {
		out[pnames[i]] = 0.0;
	}
}

void FileWriter::printLine() {
	for (int i = 0; i < noutput; i++) {
		*Sfile << out[pnames[i]] << ",";
	}
	*Sfile << endl;
}

void FileWriter::loadNames() {
	int k = 0;
	ifstream Ofile ("outputNames.txt");
	if (Ofile.is_open()) {
		while (!Ofile.eof() && k < 101) {
			Ofile >> pnames[k];
			k++;
			if (k > 100) {
				cout << "Number of allowable parameters (100) exceeded in FileWriter.cpp" << endl;
				break;
			}
		}
	noutput = k;
	Ofile.close();
	cout << noutput << " parameters read from outputNames.txt" << endl;
	} else {
		cout << "Error opening file" << endl;
	}
}

void FileWriter::closeFile() {
	Sfile->close();
}

string FileWriter::getDate() {

	  time_t rawtime;
	  struct tm * timeinfo;
	  char buffer [80];

	  time ( &rawtime );
	  timeinfo = localtime ( &rawtime );

	  strftime (buffer,80,"%m_%d_%Y_%H_%M.txt",timeinfo);
	  puts (buffer);

	  return std::string(buffer);
}
